$(function(){
    updateDepList()
    
    $('.content-title').on('click',function(){
    	toggleDown(this);
    })

    $(document).on('click','.dep-li',function(){
        console.log($(this).next('ul'))
        if($(this).next('ul').length != 0){
            toggleDown(this);
        }
    	
    })

    // 查看指定员工信息
    $(document).on('click','.icon-gengduo',function(){
        var thisId = $(this).children('input').val()
        $.ajax({
            url: "../json/staff.json",
            data: {
                id:thisId
            },
            type: "GET",
            dataType: 'json',
            success: function(data) {
                var myTemplate = Handlebars.compile($("#staff-info-template").html());
                // console.log(myTemplate(data))
                $('.staff-info-div').html(myTemplate(data));
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });
    	fadeModal('.information-modal');
    })

    // 删除员工
    $(document).on('click','.icon-lajitong',function(){
        var thisId = $(this).children('input').val();
        console.log(thisId);
    	
    	setConfirm('是否确定删除此员工',function(){
            // 
            $.ajax({
                url: "/staff/"+$('.dep-id-input').val()+"/"+thisId,
                data: {
                    id:$('.dep-id-input').val()
                },
                type: "DELECT",
                dataType: 'json',
                success: function(data) {
                    var status = data.status;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('删除员工失败！');
                    } else if (status == 202) {
                        $('tr').removeClass('selected');
                        $(this).parents('tr').first().addClass('selected');
                        $('.selected').remove();
                        setAlert('删除员工成功');
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
    		
    	})
    })

    // 修改部门信息模态框（内容页）
    $('.edit-btn').on('click',function(e){
        // 填充表单
        $('.form-control .dep-name').val($('.dep-info-name').html()),//部门名称
        $('.dep-type').val($('.dep-info-type').html()),//部门类别
        $('.dep-num').val($('.dep-info-num').html()),//部门编号
        $('.dep-date').val($('.dep-info-date').html()),//创建日期
        $('.dep-fax').val($('.dep-info-fax').html()),//传真
        $('.dep-phone').val($('.dep-info-phone').html()),//电话
        $('.area-name').val($('.area-info-name').html()),//区域名称
        $('.area-site').val($('.dep-info-site').html());//区域地址
        $('.dep-btn').attr('class','btn dep-btn edit-dep-btn');
    	fadeModal('.edit-modal');
    })

    $('.add-btn').on('click',function(){
    	fadeModal('.add-modal');
    })

    // 修改部门
    $(document).on('click','.edit-dep-btn',function(){
    	// console.log(validateDep());
    	if(validateDep() != undefined){
            $.ajax({
                url: "/department/",
                data: {
                    department_name: validateDep().depName,
                    department_id:validateDep().depNum,
                    department_Type:validateDep().depType,
                    department_address:validateDep().areaSite,
                    department_phone:validateDep().depPhone,
                    department_fax:validateDep().depFax,
                    department_area_name:validateDep().areaName
                },
                type: "PUT",
                dataType: 'json',
                success: function(data) {
                    var status = data.status;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('修改失败！');
                    } else if (status == 202) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        // fillDep('修改成功',
                        // validateDep().depName,
                        // validateDep().depType,
                        // validateDep().depNum,
                        // validateDep().depFax,
                        // validateDep().depPhone,
                        // validateDep().areaName,
                        // validateDep().areaSite);
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
    		
    	}
    });

    $('.dep-cancel-btn').on('click',function(){
    	$('.edit-modal,.mask').fadeOut();
    });

    $('.dep-date').fdatepicker();

    $(document).on('click','.btn-info',function(){
    	$('.information-modal,.mask').fadeOut();
    });

    $(document).on('mousedown','.dep-li',function(e){
        var depId = $(this).children('dep-li-id').val();
        var depPreId = $(this).children('dep-li-pre-id').val();
        $('.dep-id-input').val(depId);
        $('.dep-pre-id-input').val(depPreId);
		//屏蔽右键菜单
		document.oncontextmenu=function(){
			return false;
		}

		if(e.which == 3){

			$('.dep-li').removeClass('selected');
			$(this).addClass('selected');
			$('.right-menu').css({
				'left':mousePos(e).x,
				'top':mousePos(e).y
			})
			$('.right-menu').fadeIn();
		}

		return false;
    })

    $(document).click(function(){
    	$('.right-menu').hide()
    })

    // 创建部门、创建子部门模态框
    $('.creat-dep,.creat-child-dep').click(function(){
        // 清空表单
        $('.form-control .dep-name').val(''),//部门名称
        $('.dep-type').val(''),//部门类别
        $('.dep-num').val(''),//部门编号
        // depDate = $('.dep-date').val(),//创建日期
        $('.dep-fax').val(''),//传真
        $('.dep-phone').val(''),//电话
        $('.area-name').val(''),//区域名称
        $('.area-site').val('');//区域地址
        // 改变按钮class
        $('.dep-btn').attr('class','btn dep-btn creat-dep-btn')
    	fadeModal('.edit-modal');
    })

    // 创建部门、创建子部门
    $(document).on('click','.creat-dep-btn',function(){
        // console.log(validateDep());
        if(validateDep() != undefined){
            $.ajax({
                url: "/department/",
                data: {
                    department_name: validateDep().depName,
                    department_id:validateDep().depNum,
                    department_Type:validateDep().depType,
                    department_address:validateDep().areaSite,
                    department_phone:validateDep().depPhone,
                    department_fax:validateDep().depFax,
                    department_area_name:validateDep().areaName
                },
                type: "POST",
                dataType: 'json',
                success: function(data) {
                    var status = data.status;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('部门创建失败失败！');
                    } else if (status == 202) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        setAlert('部门创建成功');
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
            
        }
    });

    // 修改右键菜单模态框（右键菜单）
    $('.edit-dep').click(function(){
        $.ajax({
            url: "../json/dep-information.json",
            data: {
                id:$('.dep-id-input').val()
            },
            type: "GET",
            dataType: 'json',
            success: function(data) {
                $('.form-control .dep-name').val(data.Name),//部门名称
                $('.dep-type').val(),//部门类别
                $('.dep-num').val(data.Id),//部门编号
                // $('.dep-date').val(data.CreateTime),//创建日期
                $('.dep-fax').val(data.Fax),//传真
                $('.dep-phone').val(data.Phone),//电话
                $('.area-name').val(data.AreaName),//区域名称
                $('.area-site').val(data.Address);//区域地址
                $('.dep-btn').attr('class','btn dep-btn edit-dep-btn');
                fadeModal('.edit-modal');
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });
        
    })

    // 删除部门
    $('.delete-dep,.delete-dep-btn').click(function(){
    	setConfirm('确认删除此部门？',function(){
            $.ajax({
                url: "/department/",
                data: {
                    id:$('.dep-id-input').val()
                },
                type: "DELECT",
                dataType: 'json',
                success: function(data) {
                    var status = data.status;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('删除部门失败！');
                    } else if (status == 202) {
                        updateDepList();
                        setAlert('部门删除成功');
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
    		
    	})
    })

    $('.dep-search-btn').click(function(){
    	var searchContent = $('.dep-search-input').val();
    	for(var i=0;i<$('.dep-li').length;i++){
    		console.log($('.dep-li').eq(i).text())
    		if($('.dep-li').eq(i).text() == searchContent){
    			$('.dep-li').eq(i).click();
    		}    		
    	}
    })
    
})

var content = "";

/**
 * [creatDeplist 创建部门列表]
 * @param  {[Object]} data [部门数据]
 * @return {[String]} content [DOM结构]
 */
function creatDeplist(data){
	content += "<ul>";
	for(var i =0;i<data.length;i++){		
		if(data[i].sub == ""){
			content += '<li class="dep-li">'+
                '<span class="dep-name">'+data[i].name+'</span>'+
                '<input type="hidden" value="'+data[i]._id+'" class="dep-li-id">'+
                '<input type="hidden" value="'+data[i].preId+'" class="dep-li-pre-id">'+
                '</li>';
		}else{
			content += '<li class="dep-li">'+
                '<i class="iconfont icon-xiala"></i>'+
                '<span class="dep-name">'+data[i].name+'</span>'+
                '<input type="hidden" value="'+data[i]._id+'" class="dep-li-id">'+
                '<input type="hidden" value="'+data[i].preId+'" class="dep-li-pre-id">'+
                '</li>';
			creatDeplist(data[i].sub);
		}
	}
	content += "</ul>";
	return content;
}

/**
 * [updateDepList 更新部门列表]
 * @param  {[type]} id [所显示的部门id]
 */
function updateDepList(id){
    $.ajax({
        url: "../json/dep.json",
        type: "GET",
        dataType: 'json',
        success: function(data) {
            // console.log(data)
            // var dep = JSON.parse(data);
            $('.dep-list').html(creatDeplist(data)); 
            // 面包屑导航,默认显示第一个部门
            if(id == undefined){
                var thisData = data[0];
                while(thisData.sub != ""){
                    thisData = thisData.sub[0];
                }
                console.log()
                setBread(thisData._id);
                viewDepInfor(thisData._id);
                viewStaffInfor(thisData._id);
                
                
            }else{
                setBread(id)
            }                
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

/**
 * [validateDep 部门操作验证]
 * @return {[Object]} [部门信息]
 */
function validateDep(){
	var depName = $('.form-control .dep-name').val(),//部门名称
		depType = $('.dep-type').val(),//部门类别
		depNum = $('.dep-num').val(),//部门编号
		// depDate = $('.dep-date').val(),//创建日期
		depFax = $('.dep-fax').val(),//传真
		depPhone = $('.dep-phone').val(),//电话
		areaName = $('.area-name').val(),//区域名称
		areaSite = $('.area-site').val();//区域地址
    	if(depName == ''){
    		setAlert('请填写部门名称');
    	}else if(depType == ''){
    		setAlert('请输入部门类别');
    	}else if(depPhone == ''){
    		setAlert('请输入电话号码');
    	}else if(areaSite == ''){
    		setAlert('请输入区域所在地');
    	}else{
    		return {
    			depName:depName,
    			depNum:depNum,
    			depFax:depFax,
    			depPhone:depPhone,
    			areaName:areaName,
    			areaSite:areaSite
    		}
    	}
}

/**
 * [fillDep 填充信息面板]
 * @param  {[String]} string   [提示文字]
 * @param  {[String]} depName  [部门名称]
 * @param  {[String]} depType  [部门类别]
 * @param  {[String]} depNum   [部门编号]
 * @param  {[String]} depFax   [部门传真]
 * @param  {[String]} depPhone [部门电话]
 * @param  {[String]} areaName [区域名称]
 * @param  {[String]} areaSite [区域地址]
 */
function fillDep(string,depName,depType,depNum,depFax,depPhone,areaName,areaSite){
	setAlert(string);
	$('.dep-info-name').html(depName);
	$('.dep-info-type').html(depType);
	$('.dep-info-num').html(depNum);
	// $('.dep-info-date').html(depDate);
	$('.dep-info-fax').html(depFax);
	$('.dep-info-phone').html(depPhone);
	$('.area-info-name').html(areaName);
	$('.dep-info-site').html(areaSite);
	$('.edit-modal').fadeOut();
}

/**
 * [mousePos 获取浏览器坐标]
 * @param  {[type]} e [description]
 * @return {[type]}   [x,y坐标]
 */
function mousePos(e){ 
  var x,y; 
  var e = e||window.event; 
  return { 
    x:e.clientX+document.body.scrollLeft + document.documentElement.scrollLeft, 
    y:e.clientY+document.body.scrollTop + document.documentElement.scrollTop 
  }; 
}; 

/**
 * [setBread 面包屑导航]
 * @param {[Object]} tipBottom [指定部门id]
 */
var depObj = [];
function setBread(id){
    // console.log(id)
    var idList = $('.dep-li-id');
    var breadcrumb = '';
    // console.log(idList.length)
    for(var i=0;i<idList.length;i++){
        // console.log(id);

        var idListVal = parseInt(idList.eq(i).val());
        // console.log(idListVal)
        if(id == idListVal){
            // console.log('-------------------------------')
            var depName = $('.dep-name').eq(i).text();
            console.log(depName)
            var preId = $('.dep-li-pre-id').eq(i).val();
            // console.log(depName)
            depObj.push({
                id:id,
                preId:preId,
                name:depName
            })
            if(preId != -1){
                setBread(preId);
                // console.log(preId)   
            }else{
                console.log(depObj)
                return depObj;
            }
        }
    }
    if(depObj != ''){
        for(var j=depObj.length-1;j>=0;j--){
            breadcrumb += '<a href="#" title="'+depObj[j].name+'" class="tip-bottom">'+
                            '<i class="iconfont icon-home"></i>'+
                            depObj[j].name+
                            '<input type="hidden" value="'+depObj[j].id+'">'+
                          '</a>';
        }
        console.log(breadcrumb)
        $('#breadcrumb').html(breadcrumb);
    }
}

/**
 * [viewDepInfor 查询指定部门信息]
 * @param  {[type]} id [指定部门id]
 */
function viewDepInfor(id){
    $.ajax({
        url: "../json/dep-information.json",
        data: {
            id:id
        },
        type: "GET",
        dataType: 'json',
        success: function(data) {
            var myTemplate = Handlebars.compile($("#dep-info-template").html());
            $('.dep-information').html(myTemplate(data));
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

/**
 * [viewStaffInfor 查询指定部门的员工信息]
 * @param  {[type]} id [指定部门id]
 */
function viewStaffInfor(id){
    $.ajax({
        url: "../json/link-staff.json",
        data: {
            id:id
        },
        type: "GET",
        dataType: 'json',
        success: function(data) {
            var myTemplate = Handlebars.compile($("#staff-template").html());
            console.log(myTemplate(data))
            $('.staff-body').html(myTemplate(data));
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

